<script>
    import Box from './box.svelte'
    import {onMount} from "svelte";
    import messages from "../store.js";
    import {fileList} from "../store.js";
    import {thisuser, ws} from "../src/main.js";

    let photos = [];
    onMount(async () => {
        // const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`);
        // photos = await res.json();

        // var form=document.getElementById('form')
        // form.onsubmit = function(){
        //     let data = new FormData(this);
        //     fetch("http://localhost:9999/api/fileupload",{
        //         headers:{
        //         },
        //         method:"POST",
        //         // fetch 的 body 发送 data
        //         body:data
        //     }).then(res=>res.json()).then(json=>console.log(json));
        // }
        fetch("/api/getfile",{
            method:"Get"
        }).then((r)=>{
            return r.json()
        }).then((res)=>{
            fileList.update(cur =>{
                return res.files
            })
        })
    });
    function downloadfile(name) {
        fetch("/api/downloadfile",{
            method:'Post',
            body:JSON.stringify({
                file:name
            })
        }).then(async (res)=>{
            let data=await res.blob()
            console.log(data)
            const filename=name
            // console.log(res.data)
            // console.log(res.headers)
            const blob=new Blob([data])

            // //获取文件名
            // const fileName = res.headers["content-disposition"].split(";")[1].split("=")[1]
            // const blob = new Blob([res.data]);
            // //创建一个a标签并设置href属性，之后模拟人为点击下载文件
            let link = document.createElement('a');
            document.body.appendChild(link)         // 没什么效果，remove
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;//设置下载文件名
            link.click();//模拟点击
            // //释放资源并删除创建的a标签
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link)
        })
    }

    function delfile(name) {
        console.log(name)
        var msg = "确定删除？";

        if (confirm(msg) === true) {
            fetch("/api/delfile", {
                method: "Post",
                body: JSON.stringify({
                    file:name
                })
            }).then((r) => {
                return r.json()
            }).then((r) => {
                console.log(r)
                if (r.status === 0) {
                    alert("删除成功")
                    // ws.send(JSON.stringify({
                    //     "type":4,
                    //     "from":thisuser,
                    //     "msg":"文件列表更新"
                    // }))
                } else {
                    alert("删除失败")
                }
            })
        } else {

        }
    }

    function updatefile() {

    }

</script>
<style>
    .file{
        width: 90%;
        height: 200px;
        overflow-y: scroll;
        /*align-content: center;*/
        border: 1px solid #aaa;
        border-radius: 2px;
        box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
        padding: 1em;
        margin: 1em 1em;
    }
    .showfile {
        width: 90%;
        height: 330px;
        overflow-y: scroll;
        /*align-content: center;*/
        border: 1px solid #aaa;
        border-radius: 2px;
        box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
        padding: 1em;
        margin: 1em 1em;
    }
</style>

<main class="mainfile" style="width: 25%;margin-right: 15px">
    <div class="file" style="float: top;">
    <h3>文件上传</h3>
    <form id="form" method="post" action="/api/fileupload" target="_blank" enctype="multipart/form-data">
        选择一个文件:
        <br/>
        <input type="file" name="uploadFile" style="margin: 1em;border: solid 1px"/>
        <br/><br/>
        <input type="submit" value="上传" style="width: 65%;height: 30px"/>
    </form>
    </div>
    <div style="float: bottom" class="showfile">
<!--        <div class="photos">-->
<!--            {#each photos as photo}-->
<!--                <figure>-->
<!--                    <img src={photo.thumbnailUrl} alt={photo.title}>-->
<!--                    <figcaption>{photo.title}</figcaption>-->
<!--                </figure>-->
<!--            {:else}-->
<!--                &lt;!&ndash; this block renders when photos.length === 0 &ndash;&gt;-->
<!--                <p>loading...</p>-->
<!--            {/each}-->
<!--        </div>-->
        {#each $fileList as {name,size}}
            <div style="border: solid 1px;padding: 3px">
                <span on:click={()=>downloadfile(name)}>{name}</span>
                <button style="border: 0;float: right; visibility: {thisuser==='admin'?'visible':'hidden'}"
                    on:click={()=>delfile(name)}>delete</button>
            </div>
<!--            <button type="submit" onclick="window.location.href='testceshi.html'">返回</button>-->
<!--            <a href="testceshi.html"><button type="submit">链接</button></a>-->
        {:else }
            <span>Loading...</span>
        {/each}
    </div>
</main>